package com.waq.controller;

import com.waq.pojo.User;
import com.waq.service.UserService;
import com.waq.utils.WAQJSONResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("user")
@RestController
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public WAQJSONResult register(@RequestParam String username, @RequestParam String password,
                                  @RequestParam String confirmPwd, @RequestParam String position) throws Exception {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)
                || StringUtils.isBlank(confirmPwd)) {
            return WAQJSONResult.errorMsg("用户名或密码为空");
        }
        if (userService.queryUsernameIsExist(username)) {
            return  WAQJSONResult.errorMsg("用户名已存在");
        }
        if (!password.equals(confirmPwd)) {
            return WAQJSONResult.errorMsg("两次密码输入不一致");
        }
        User user = userService.register(username, password, position);
        if (user == null) {
            return WAQJSONResult.errorMsg("用户注册失败");
        }
        return WAQJSONResult.ok();
    }
    @PostMapping("/login")
    public WAQJSONResult login(@RequestParam String username, String password,
                               HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return WAQJSONResult.errorMsg("用户名或密码为空");
        }
        //验证密码是否正确【传给service的是加密后的密码】
        User user = userService.queryUserForLogin(username, password);
        //用户不存在
        if (user == null) {
            return WAQJSONResult.errorMsg("用户名或密码错误");
        }
        //将登录凭证加入到用户登陆成功的session内
        httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        httpServletRequest.getSession().setAttribute("LOGIN_USER", user);
        User userCopy = (User)httpServletRequest.getSession().getAttribute("LOGIN_USER");
//        httpServletResponse.addHeader("access-control-allow-origin", "*");
        return WAQJSONResult.ok();
    }
}
